﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

using BawangMemo.BackendModels;
using System.Threading;

namespace BawangMemo.BawangMemoView.View
{
    /// <summary>
    /// NewCourseView.xaml 的交互逻辑
    /// </summary>
    public partial class NewCourseView : UserControl
    {
        IntroWindow introWindow;
        //LoadView loadView;

        public NewCourseView()
        {
            InitializeComponent();
            Initialize();
        }

        public NewCourseView(IntroWindow introWindow)
        {
            this.introWindow = introWindow;
            //loadView = new LoadView(introWindow);
            InitializeComponent();
            Initialize();
        }

        #region Update

        public void Initialize()
        {
            List<string> bookList = new List<string>();
            string[] books = Directory.GetFiles("./AppData/Book");
            foreach (string book in books)
            {
                string bookName = new FileInfo(book).Name.Substring(0, new FileInfo(book).Name.Length - 4);
                bookList.Add(bookName);
            }
            listbox1.ItemsSource = bookList;
        }

        public void UpdateButton()
        {
            if (listbox1.SelectedIndex == -1)
                return;

            if (CourseRepository.hasCourseName(textbox1.Text))
            {
                labelCourseName.Content = "课程名称" + "  (已存在)";
                createButton.IsEnabled = false;
            }
            else if (textbox1.Text.Equals(""))
            {
                labelCourseName.Content = "课程名称";
                createButton.IsEnabled = false;
            }
            else if (!ViewUtil.IsValidCourseName(textbox1.Text))
            {
                labelCourseName.Content = "课程名称" + "   (只含中英文数字和下划线)";
                createButton.IsEnabled = false;
            }
            else
            {
                labelCourseName.Content = "课程名称";
                createButton.IsEnabled = true;
            }
        }

        #endregion

        #region Events
        
        Thread loadThread;

        private void createButton_Click(object sender, RoutedEventArgs e)
        {
            WordOrder order = WordOrder.Sequential;
            if (radioButton2.IsChecked.Value)
                order = WordOrder.Reversal;
            else if (radioButton3.IsChecked.Value)
                order = WordOrder.Randomized;
            
            //wintokk: ask the user whether to load the predefined tags
            var r = MessageBox.Show(introWindow, "导入预置标签吗?\n可能需要几秒钟...", "导入标签",
                MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);

//            if (r == MessageBoxResult.Yes)
//            {
            //loadView.Show();
            introWindow.IsEnabled = false;
//            }
            ThreadCreateCourse loadCourse = new ThreadCreateCourse(textbox1.Text, listbox1.SelectedItem.ToString(), (int)slider1.Value, order, r == MessageBoxResult.Yes, this);
            loadThread = new Thread(new ThreadStart(loadCourse.threadProc));
            loadThread.Start();
        }

        delegate void LoadFinishHandler();

        private void endLoading()
        {
            if (Dispatcher.CheckAccess())
            {                
                //loadView.Close();
                introWindow.IsEnabled = true;
                
                CourseWrapper cw = CourseRepository.LoadCourse(textbox1.Text);
                if (loadThread.IsAlive)
                    loadThread.Abort();
                new MainWindow(cw).Show();
                App.IsShuttingDown = false;
                introWindow.Close();
                App.IsShuttingDown = true;
            }
            else
            {
                LoadFinishHandler finishHandler = new LoadFinishHandler(endLoading);
                this.Dispatcher.BeginInvoke(finishHandler);
            }
        }

        private class ThreadCreateCourse
        {
            String courseName;
            String selectedBook;
            int wordNum;
            WordOrder order;
            bool flag;
            NewCourseView p;
            public ThreadCreateCourse(String cn, String sb, int wn, WordOrder o, bool f, NewCourseView pa)
            {
                courseName = cn;
                selectedBook = sb;
                wordNum = wn;
                order = o;
                flag = f;
                p = pa;
            }
            public void threadProc()
            {
                CourseRepository.CreateCourse(courseName, "AppData/Book/" + selectedBook + ".xml",
                        order, wordNum, flag);
                p.endLoading();
            }
        }

        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            label1.Content = "每日生词：" + ((int)slider1.Value).ToString();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            UpdateButton();
        }

        private void listbox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateButton();
        }

        #endregion
    }
}
